package org.mq.mymq.nameserver.event.listener;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.mq.mymq.common.coder.TcpMsg;
import org.mq.mymq.common.dto.ServiceRegistryRespDTO;
import org.mq.mymq.common.enums.NameServerResponseCode;
import org.mq.mymq.common.event.Listener;
import org.mq.mymq.nameserver.common.CommonCache;
import org.mq.mymq.nameserver.enums.ReplicationModeEnum;
import org.mq.mymq.nameserver.enums.ReplicationMsgTypeEnum;
import org.mq.mymq.nameserver.event.model.RegistryEvent;
import org.mq.mymq.nameserver.event.model.ReplicationMsgEvent;
import org.mq.mymq.nameserver.store.ServiceInstance;
import org.mq.mymq.nameserver.utils.NameserverUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * @ClassName RegistryListener
 * @Description 注册事件监听器
 * @Author jiarong_ye
 * @Date 2025/6/19 13:22
 * @Version 1.0
 */
public class RegistryListener implements Listener<RegistryEvent> {

    private static final Logger log = LoggerFactory.getLogger(RegistryListener.class);

    @Override
    public void onReceive(RegistryEvent event) {
        // 安全认证
        boolean isVerify = NameserverUtil.isVerify(event.getUser(), event.getPassword());
        ChannelHandlerContext ctx = event.getChannelHandlerContext();
        if (!isVerify) {
            ServiceRegistryRespDTO serviceRegistryRespDTO = new ServiceRegistryRespDTO();
            serviceRegistryRespDTO.setMsgId(event.getMsgId());
            TcpMsg tcpMsg = new TcpMsg(NameServerResponseCode.ERROR_USER_OR_PASSWORD.getCode(),
                    JSON.toJSONBytes(serviceRegistryRespDTO));
            ctx.writeAndFlush(tcpMsg);
            ctx.close();
            throw new IllegalArgumentException("Invalid user or password");
        }
        log.info("接收注册事件：{}", JSON.toJSONString(event));
        ctx.attr(AttributeKey.valueOf("reqId")).set(event.getIp() + ":" + event.getPort());
        ServiceInstance serviceInstance = new ServiceInstance();
        serviceInstance.setIp(event.getIp());
        serviceInstance.setPort(event.getPort());
        serviceInstance.setRegistryType(event.getRegistryType());
        serviceInstance.setAttrs(event.getAttrs());
        serviceInstance.setFirstRegistryTime(System.currentTimeMillis());
        CommonCache.getServiceInstanceManager().put(serviceInstance);
        ReplicationModeEnum replicationModeEnum = ReplicationModeEnum.of(CommonCache.getNameserverProperties().getReplicationMode());
        if (replicationModeEnum == null) {
            // 单机架构，不做复制处理，直接返回成功
            // todo
            String msgId = event.getMsgId();
            ServiceRegistryRespDTO serviceRegistryRespDTO = new ServiceRegistryRespDTO();
            serviceRegistryRespDTO.setMsgId(msgId);
            TcpMsg tcpMsg = new TcpMsg(NameServerResponseCode.REGISTRY_SUCCESS.getCode(),
                    JSON.toJSONBytes(serviceRegistryRespDTO));
            ctx.writeAndFlush(tcpMsg);
            return;
        }
        // 当前是主从复制模式且当前角色为主节点，则往队列里放元素
        ReplicationMsgEvent replicationMsgEvent = new ReplicationMsgEvent();
        replicationMsgEvent.setServiceInstance(serviceInstance);
        replicationMsgEvent.setMsgId(UUID.randomUUID().toString());
        replicationMsgEvent.setChannelHandlerContext(ctx);
        replicationMsgEvent.setType(ReplicationMsgTypeEnum.REGISTRY.getCode());
        CommonCache.getReplicationMsgQueueManager().put(replicationMsgEvent);
    }
}
